define(["jquery", "authConfig", "dataUtil", "jquery_ext_purl"], function ($, authConfig, dataUtil, purl) {
    function doAuth(successCallback, failCallBack) {
        ajaxSetup();
        if (findToken()) {
            refreshToken(successCallback, failCallBack);
        } else {
            if(failCallBack){
                failCallBack();
            }
        }
    }

    function ajaxSetup() {
        $.ajaxSetup({
            headers: {
                "Authorization": findToken()
            }
        });
    }

    function toLogin() {
        var redirectUrl = purl().param("redirectUrl");
        if (!redirectUrl) {
            var url = authConfig.LOGIN_PAGE_URL;
            if (authConfig.LOGIN_PAGE_URL.indexOf("?") < 0) {
                url += "?";
            } else {
                url += "&";
            }
            url += "redirectUrl=" + window.location.href;
            window.location.href = url;
        }
    }

    function doLogin(userId, password) {
        $.ajax({
            url: authConfig.JWT_LOGIN_URL,
            type: "POST",
            data: { // 默认添加请求头
                "userId": userId,
                "password": password
            },
            dataType: "JSON",
            beforeSend: function (xhr, request) {
                cleanToken();
                console.info("开始登陆...");
            },
            success: function (resultData) {
                if (dataUtil.isSuccess(resultData)) {
                    console.info("登陆成功.");
                    if (resultData.data && resultData.data.token) {
                        processToken(resultData);
                        var redirectUrl = purl().param("redirectUrl");
                        if (redirectUrl) {
                            window.location.href = redirectUrl;
                        }
                    } else {
                        console.warn("登陆成功，但无法获取到鉴权信息.");
                    }
                } else {
                    var info = "登陆失败." + resultData.msg ? resultData.msg : "";
                    toLogin(info);
                    console.warn(info);
                }
            },
            error: processError
        });
    }

    function processError(event, xhr, options, exc) {
        if (event.status == 401) {
            var msg = "";
            if (event.responseJSON && event.responseJSON.msg) {
                msg = event.responseJSON.msg;
            }
            alert("登陆失败. " + msg);
        }
    }

    function processToken(resultData) {
        saveToken(resultData.data.token);
        ajaxSetup();
        if (!isNaN(resultData.data.nextRefreshSeconds)) {
            window.setTimeout(function () {
                var token = findToken();
                if (token) {
                    refreshToken();
                } else {
                    toLogin();
                }
            }, resultData.data.nextRefreshSeconds * 1000);
        }
    }

    function saveToken(token) {
        cleanToken();
        window.localStorage.setItem("XDH_JWT_TOKEN", token);
    }

    function cleanToken() {
        window.localStorage.removeItem("XDH_JWT_TOKEN");
    }

    function findToken() {
        var token;
        if (window.localStorage) {
            token = window.localStorage.getItem("XDH_JWT_TOKEN");
        }
        return token;
    }

    function refreshToken(successCallback, failCallBack) {
        $.ajax({
            url: authConfig.REFRESH_TOKEN_URL,
            type: "POST",
            dataType: "JSON",
            beforeSend: function (xhr, request) {
                console.info("开始刷新鉴权信息...");
            },
            success: function (resultData) {
                if (dataUtil.isSuccess(resultData)) {
                    console.info("刷新鉴权成功，鉴权信息有效.");
                    processToken(resultData);
                    if (successCallback) {
                        successCallback(resultData);
                    }
                } else {
                    cleanToken();
                    if (failCallBack) {
                        failCallBack(resultData);
                    }
                    console.warn("刷新鉴权信息失败." + resultData.msg ? resultData.msg : "");
                }
            },
            error: function (event, xhr, options, exc) {
                processError(event, xhr, options, exc);
                if (failCallBack) {
                    failCallBack();
                }
            }
        });
    }

    return {
        doAuth: doAuth,
        doLogin: doLogin,
        toLogin: toLogin
    }
});